package util;

import java.io.IOException;
import java.util.Map;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.IOUtils;

import com.alibaba.fastjson.JSONObject;

public class HttpIOUtil {
	
	public static JSONObject requestToJson(HttpServletRequest request) {
		JSONObject jsonobj = null;
		try {
			String json = IOUtils.toString(request.getInputStream(), "UTF-8");
			// System.out.println(json);
			jsonobj = JSONObject.parseObject(json);
			// System.out.println("转json成功！");
		} catch (IOException e) {
			System.out.println("转json失败！");
			e.printStackTrace();
		}
		return jsonobj;
	}

	// 输出json数据到页面
	@SuppressWarnings("static-access")
	public static void ObjectToWeb(HttpServletResponse response, Object out) {
		try {
			response.setHeader("content-type", "text/html;charset=UTF-8");
			response.getWriter().write(new net.sf.json.JSONObject().fromObject(out).toString());
			// System.out.println("json写入respons成功!");
		} catch (IOException e) {
			System.out.println("json写入respons失败!");
			e.printStackTrace();
		}
	}
	
	// 将传入的request中的值转为JSON对象
	public static JSONObject requestParameterToJsonObject(HttpServletRequest request) {
		JSONObject out = new JSONObject();
		Map<String, String[]> map = request.getParameterMap();
		Set<String> keys = map.keySet();
		for(String key : keys){
			if(map.get(key).length > 1){
				out.put(key, map.get(key));
			} else if(map.get(key).length == 1) {
				out.put(key, map.get(key)[0]);
			} else {
				out.put(key, null);
			}
		}
		return out;
	}
}
